package com.grandbroad.eim.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.login.bean.ReturenUser;
import com.google.gson.Gson;
import com.grandbroad.eim.app.MyApplication;
import com.grandbroad.eim.entry.WechatLoginEvent;
import com.grandbroad.eim.entry.WhcatBean;
import com.grandbroad.eim.ui.activities.HomeActivity;
import com.grandbroad.eim.ui.activities.RegisterActivity;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String APP_SECRET = MyApplication.WX_SCRECT;
    private IWXAPI mWeixinAPI;
    public static final String WEIXIN_APP_ID = MyApplication.WX_ID;
    private static String uuid;
    //登陆api
    private String WECHAT_LOGIN = Constants.BASE_URL+"wechatauth/appLogin";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWeixinAPI = WXAPIFactory.createWXAPI(this, WEIXIN_APP_ID, true);
        mWeixinAPI.handleIntent(this.getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWeixinAPI.handleIntent(intent, this);//必须调用此句话
    }

    //微信发送的请求将回调到onReq方法
    @Override
    public void onReq(BaseReq req) {

    }

    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:

                //发送成功
                SendAuth.Resp sendResp = (SendAuth.Resp) resp;
                if (sendResp != null) {
                    String code = sendResp.code;
                    getAccess_token(code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:

                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:

                //发送被拒绝
                break;
            default:
                //发送返回
                break;
        }

    }

    /**
     * 获取openid accessToken值用于后期操作
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + WEIXIN_APP_ID
                + "&secret="
                + APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";

        //网络请求，根据自己的请求方式
        RequestParams params = new RequestParams(path);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String openid = jsonObject.getString("openid").toString().trim();
                    String access_token = jsonObject.getString("access_token").toString().trim();
                    //以上为获取微信openid
                    getUserMesg(access_token, openid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    /**
     * 获取微信的个人信息
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;

        //网络请求，根据自己的请求方式
        RequestParams params = new RequestParams(path);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    Gson gson = new Gson();
                    WhcatBean bean = gson.fromJson(result,WhcatBean.class);
                    if (bean!=null)
                    {
                        //保存从微信获取的实体
                        Hawk.put("wechat",bean);
                        //请求鼹鼠后台
                        requsetMole(bean);
                    }
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 请求鼹鼠后台
     * @param bean
     */
    private void requsetMole(final WhcatBean bean) {
        RequestParams params =new RequestParams(WECHAT_LOGIN);
        params.addBodyParameter("unionId",bean.getUnionid());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    ReturenUser user = new Gson().fromJson(result,ReturenUser.class);
                    //直接前往首页
                    if (user!=null)
                    {
                        //发送给Login
                        MyApplication.exitLoginActivity(WXEntryActivity.this);
                        CacheUtils.saveUser(user.getData());
                        EventBus.getDefault().post(new WechatLoginEvent(user));
                        finish();
                    }
                    else
                    {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("mode",true);
                        bundle.putString("unbindid",result);
                        bundle.putString("name",bean.getNickname());
                        bundle.putString("avatar",bean.getHeadimgurl());
                        Intent intent = new Intent(WXEntryActivity.this,RegisterActivity.class);
                        intent.putExtras(bundle);
                        ToastUtils.show("未绑定账号，请注册新账号并绑定");
                        startActivity(intent);
                        finish();
                    }

                }
                catch (Exception e)
                {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("mode",true);
                    bundle.putString("unbindid",result);
                    bundle.putString("name",bean.getNickname());
                    bundle.putString("avatar",bean.getHeadimgurl());
                    Intent intent = new Intent(WXEntryActivity.this,RegisterActivity.class);
                    intent.putExtras(bundle);
                    ToastUtils.show("未绑定账号，请注册新账号并绑定");
                    startActivity(intent);
                    finish();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
